package ua.kyivenergo.cableLines.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ua.kyivenergo.cableLines.data.GenericObject;
import ua.kyivenergo.cableLines.data.database.DataManager;
import ua.kyivenergo.cableLines.search.SearchSystem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;


/**
 * Created by Alex Kebkalo (kebka@mail.ru) on 16.04.14.
 */

@Controller
public class CableLinesController {
    DataManager dataManager;
    SearchSystem searchSystem;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/login/", method = RequestMethod.POST)
    public String login(HttpServletRequest request, String userName, String password) {
        if (!userName.equals("test") || !password.equals("testpassword")) {
            request.setAttribute("message", "Неверное имя пользователя или пароль. Попробуйте еще раз");
            return "index";
        }
        List<GenericObject> objects = null;
        try {
            dataManager = new DataManager();
            objects = dataManager.loadCableLines();
        }
        catch (Exception e) {
            request.setAttribute("errorMessage", "Ошибка MySQL." + e.getMessage());
        }
        request.setAttribute("cableLines", objects);
        searchSystem = new SearchSystem(objects);
        return "main";
    }

    @RequestMapping(value = "/search/", method = RequestMethod.POST)
    public String search(HttpServletRequest request, String searchString) {
        request.setAttribute("cableLines", searchSystem.performSearch(searchString));
        request.setAttribute("searchString", searchString);
        return "main";
    }

    @RequestMapping(value = "/logout/", method = RequestMethod.GET)
    public String logout() {
        return "index";
    }

    @RequestMapping(value = "/get_file", method = RequestMethod.GET)
    public String getFile(HttpServletRequest request, HttpServletResponse response, String id) {
        byte[] imgData;
        try {
             imgData = dataManager.getBinary(id);
        }
        catch (Exception e) {
            request.setAttribute("errorMessage", "Ошибка MySQL." + e.getMessage());
            return "main";
        }
        try {
            response.setContentType("image/gif");
            OutputStream output = response.getOutputStream();
            output.write(imgData);
            output.flush();
            output.close();
        }
        catch (Exception e) {
            request.setAttribute("errorMessage", "Ошибка вывода." + e.getMessage());
            return "main";
        }
        return "main";
    }
}
